package com.csnf.dao;

import com.csnf.entity.User;
import com.csnf.util.JdbcUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDao {

    /**
     * 全部用户信息
     * @return
     * @throws SQLException
     */
    public List<User> getAll() throws SQLException {
        String sql = "select user_id,user_name,user_nickname from user";
        Connection conn = JdbcUtil.getConnection();
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn, sql);
        ResultSet rs = ps.executeQuery();
        List<User> userList = new ArrayList<>();
        while(rs.next()){
            User user = null;
            try {
                user = JdbcUtil.invokeObject(rs, User.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            userList.add(user);
        }
        JdbcUtil.close(rs,ps,conn);  //释放资源
        return userList;
    }

    /**
     * 通过昵称查询用户信息
     * @param nickName 昵称
     * @return 用户列表
     * @throws SQLException
     */
    public List<User> getUserByNickName(String nickName) throws SQLException {
        Connection conn = JdbcUtil.getConnection();
        String sql = "select user_id,user_name,user_nickname from user where user_nickname like concat('%',?,'%')";
        PreparedStatement ps = JdbcUtil.getPreparedStatement(conn, sql, nickName);
        ResultSet rs = ps.executeQuery();
        List<User> userList = new ArrayList<>();
        while(rs.next()){
            User user = null;
            try {
                user = JdbcUtil.invokeObject(rs, User.class);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            userList.add(user);
        }
        JdbcUtil.close(rs,ps,conn);  //释放资源
        return userList;
    }

}
